import React from 'react';
import { PageContainer, ProForm, ProFormText } from '@ant-design/pro-components';
import styles from './index.less'
import { userUpdatePassword } from '@/service/user';
import { message } from 'antd';
import { history } from '@umijs/max';

const UpdatePassword: React.FC = () => {
  // 更新密码
  const updatePasswordSubmit = async (values) => {
    const {oldPassword, newPassword, confirmPassword} = values
    if (oldPassword === newPassword) {
      message.error('旧密码不能和新密码相同');
      return
    }
    
    if (newPassword !== confirmPassword) {
      message.error('新密码和确认密码必须一致');
      return
    }

    const res = await userUpdatePassword(values)
    if (res) {
      message.success('密码修改成功，将在3秒后自动退出登录，请重新输入密码后再登录')

      setTimeout(() => {
        history.replace('/login')
        return
      }, 3000)
    }
  };

  return (
    <PageContainer
      header={{ breadcrumb: false, title: false }}
      className={styles.pageWrapper}
    >
      <ProForm
        submitter={{
          resetButtonProps: false,
        }}
        layout={'horizontal'}
        onFinish={updatePasswordSubmit}
        style={{
          display: 'inline-block',
          width: 400,
          textAlign: 'center',
        }}
      >
        <ProFormText.Password
          name="oldPassword"
          label="旧密码"
          placeholder="请输入旧密码"
          rules={[
            {
              required: true,
              message: '请输入旧密码',
            },
            {
              pattern: /^(?=.*[a-zA-Z])(?=.*\d).{8,16}$/,
              message: '请输入8-16位数字+字母的密码',
            },
          ]}
        />
        <ProFormText.Password
          name="newPassword"
          label="新密码"
          placeholder="请输入新密码（8-16位数字字母）"
          fieldProps={{ type: 'password' }}
          rules={[
            { required: true, message: '请输入新密码' },
            {
              pattern: /^(?=.*[a-zA-Z])(?=.*\d).{8,16}$/,
              message: '请输入8-16位数字+字母的密码',
            },
          ]}
        />
        <ProFormText
          name="confirmPassword"
          label="确认密码"
          placeholder="请再次输入新密码"
          fieldProps={{ type: 'password' }}
          rules={[
            { required: true, message: '请再次输入新密码' },
            {
              pattern: /^(?=.*[a-zA-Z])(?=.*\d).{8,16}$/,
              message: '请输入8-16位数字+字母的密码',
            },
          ]}
        />
      </ProForm>
    </PageContainer>
  );
};

export default UpdatePassword;
